package com.sean.community.comtroller;

import com.sean.community.entity.Event;
import com.sean.community.entity.Page;
import com.sean.community.entity.User;
import com.sean.community.event.EventProducer;
import com.sean.community.service.FollowService;
import com.sean.community.service.UserService;
import com.sean.community.util.CommunityConstant;
import com.sean.community.util.CommunityUtil;
import com.sean.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class FollowController implements CommunityConstant {
    private FollowService followService;
    private HostHolder hostHolder;
    private UserService userService;
    private EventProducer producer;

    @Autowired
    public void setFollowService(FollowService followService) {
        this.followService = followService;
    }

    @Autowired
    public void setHostHolder(HostHolder hostHolder) {
        this.hostHolder = hostHolder;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @Autowired
    public void setProducer(EventProducer producer) {
        this.producer = producer;
    }

    /**
     * 当前用户点击关注某个实体，异步请求
     * @param entityType 实体类型
     * @param entityId 实体 id
     * @return JSON 字符串
     */
    @RequestMapping(path = "/follow", method = RequestMethod.POST)
    @ResponseBody
    public String follow(int entityType, int entityId){
        User user = hostHolder.getUser();
        if(user == null){
            return CommunityUtil.getJSONString(404, "请先登录！");
        }
        followService.follow(user.getId(), entityType, entityId);
        Event event = new Event()
                .setTopic(TOPIC_FOLLOW)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(entityType)
                .setEntityId(entityId)
                .setEntityUserId(entityId);      // 目前只能关注用户
        producer.fireEvent(event);
        return CommunityUtil.getJSONString(200, "成功关注！");
    }

    /**
     * 当前用户点击关注某个实体，异步请求
     * @param entityType 实体类型
     * @param entityId 实体 id
     * @return JSON 字符串
     */
    @RequestMapping(path = "/unfollow", method = RequestMethod.POST)
    @ResponseBody
    public String unFollow(int entityType, int entityId){
        User user = hostHolder.getUser();
        if(user == null){
            return CommunityUtil.getJSONString(404, "请先登录！");
        }
        followService.unFollow(user.getId(), entityType, entityId);
        return CommunityUtil.getJSONString(200, "成功取消关注！");
    }

    @RequestMapping(path = "/followees/{userId}", method = RequestMethod.GET)
    public String getFollowees(@PathVariable("userId") int userId, Page page, Model model){
        User user = userService.findUserById(userId);
        if(user == null){
            throw new RuntimeException("用户不存在!");
        }
        model.addAllAttributes(new ModelMap("user", user));
        page.setLimit(5);
        page.setPath("/followees/" + user.getId());
        page.setRows((int)followService.findFolloweeCount(user.getId(), ENTITY_TYPE_USER));
        List<Map<String, Object>> followees = followService.findFollowees(user.getId(), page.getOffset(), page.getLimit());

        if(followees != null){
            for(Map<String, Object> map : followees){
                User targetUser = (User)map.get("targetUser");
                map.put("hasFollowed", hasFollowed(targetUser.getId()));
            }
        }
        model.addAllAttributes(new ModelMap("followees", followees));
        return "/site/followees";
    }

    @RequestMapping(path = "/followers/{userId}", method = RequestMethod.GET)
    public String getFollowers(@PathVariable("userId") int userId, Page page, Model model){
        User user = userService.findUserById(userId);
        if(user == null){
            throw new RuntimeException("用户不存在!");
        }
        model.addAllAttributes(new ModelMap("user", user));
        // 分页设置
        page.setLimit(5);
        page.setPath("/followers/" + user.getId());
        page.setRows((int)followService.findFollowerCount(ENTITY_TYPE_USER, user.getId()));
        // 查询粉丝列表
        List<Map<String, Object>> followers = followService.findFollowers(user.getId(), page.getOffset(), page.getLimit());
        if(followers != null){
            for(Map<String, Object> map : followers){
                User followerUser = (User)map.get("followerUser");
                map.put("hasFollowed", hasFollowed(followerUser.getId()));
            }
        }
        model.addAllAttributes(new ModelMap("followers", followers));
        return "/site/followers";
    }

    private boolean hasFollowed(int userId){
        User currentUser = hostHolder.getUser();
        if(currentUser == null){
            return false;
        }
        return followService.hasFollowed(currentUser.getId(), ENTITY_TYPE_USER, userId);
    }
}
